<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{Wechat, User as Users, Business, Address, Cart, Goods, GoodsSpec, Order, OrderGoods, Payment, Config, PlatClass};
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{
    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require',
        ], [
            'mobile.require' => '账号不能为空',
            'password.require' => '密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $model = new Users();
        $user = $model->where('mobile', $data['mobile'])->find();
        if (empty($user)) {
            $this->result([], 1, '用户不存在,请联系经理用户开通');
        }
        if (md5(md5($data['password'])) != $user['password']) {
            $this->result([], 1, '用户密码错误');
        }
        $token = 'user_' . md5(time() . $user['id']);
        Redis::setex($token, 7 * 86400, $user['id']);
        $this->result(['token' => $token], 0, '登录成功');
        $this->result([], 1, '登录失败');
    }

    public function info()
    {
        $user = $this->request->user;
        $this->result($user, 0, '获取成功');
    }

    public function address()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'province' => 'require',
                'city' => 'require',
                'area' => 'require',
                'address' => 'require',
                'is_default' => 'require|in:1,2'
            ], [
                'name.require' => '联系人姓名不能为空',
                'mobile.require' => '联系人电话不能为空',
                'province.require' => '省份不能为空',
                'city.require' => '城市不能为空',
                'area.require' => '区域不能为空',
                'address.require' => '具体地址不能为空',
                'is_default.require' => '默认类型不能为空',
                'is_default.in' => '默认类型不正确'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['user_id'] = $this->request->user_id;
            $addressmodel = new Address();
            if ($data['is_default'] == 2) {
                $addressmodel->where(['user_id' => $data['user_id'], 'is_default' => 2])->update(['is_default' => 1]);
            }
            if (!empty($data['id'])) {
                $res = $addressmodel->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $addressmodel->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $addressmodel = new Address();
            $result = $addressmodel->where('user_id', $this->request->user_id)->order('is_default desc')->field('user_id,created', true)->select();
            $this->result($result, 0, '操作成功');
        }
    }

    public function address_del()
    {
        $id = $this->request->post('id/d', 0);
        $addressmodel = new Address();
        $result = $addressmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function cart()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'goodsid' => 'require',
                'specid' => 'require',
                'number' => 'require',
            ], [
                'goodsid.require' => '商品ID不能为空',
                'specid.require' => '商品规格不能为空',
                'number.require' => '商品数目不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $goods = (new Goods())->where(['id' => $data['goodsid'], 'isSale' => 1, 'isdel' => 1])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            $goodsspec = (new GoodsSpec())->where(['isdel' => 1, 'goodid' => $goods['id'], 'id' => $data['specid']])->find();
            if (empty($goodsspec)) {
                $this->result([], 1, '规格产品已下架');
            }
            //查询是否已经添加购物车
            $mycart = (new Cart())->where(['specid' => $data['specid'], 'user_id' => $this->request->user_id])->find();
            $number = (int)$data['number'] ?? 0;
            if ($number < $goodsspec['starbuy'] && $number > 0) {
                $this->result([], 1, '起购数量不能低于' . $goodsspec['starbuy'] . '份');
            }
            if ($number > $goodsspec['stock']) {
                $this->result([], 1, '商品库存不足');
            }
            $save = [
                'user_id' => $this->request->user_id,
                'goodsid' => $goods['id'],
                'specid' => $goodsspec['id'],
                'number' => $number
            ];
            if (!empty($mycart)) {
                if ($number <= 0) {
                    $res = (new Cart())->where(['user_id' => $this->request->user_id, 'id' => $mycart['id']])->delete();
                } else {
                    $res =  (new Cart())->allowfield(true)->save($save, ['id' => $mycart['id']]);
                }
            } else {
                if ($number > 0) {
                    $res =  (new Cart())->allowfield(true)->save($save);
                } else {
                    $res = true;
                }
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $list = (new Cart())->where(['user_id' => $this->request->user_id])->select();
            $results = [];
            foreach ($list as $lists) {
                $good = (new Goods())->where(['id' => $lists['goodsid']])->where(['isSale' => 1, 'isdel' => 1])->field('id,title,images')->find() ?? [];
                $goodspec = (new GoodsSpec())->where('isdel', 1)->where(['id' => $lists['specid']])->field('name,price,unmit,stock,starbuy')->find() ?? [];
                if (empty($good) || empty($goodspec)) {
                    continue;
                }
                $goods = [];
                $key = 0;
                $results[$key]['name'] = '自营总店';
                $goods = [
                    'cartid' => $lists['id'],
                    'goodsid' => $lists['goodsid'],
                    'specid' => $lists['specid'],
                    'title' => $good['title'] ?? '商品已下架',
                    'images' => json_decode($good['images'] ?? '', true) ?? [],
                    'spectitle' => $goodspec['name'] ?? '规格已下架',
                    'price' => $goodspec['price'] ?? 0,
                    'unmit' => $goodspec['unmit'] ?? '',
                    'starbuy' => $goodspec['starbuy'],
                    'number' => $lists['number']
                ];
                if (empty($results[$key]['total'])) {
                    $results[$key]['total'] = $goods['price'] * $lists['number'];
                } else {
                    $results[$key]['total'] += $goods['price'] * $lists['number'];
                }
                $results[$key]['mintotal'] = (new Config())->where('name', 'mintotal')->value('value') ?? 0;
                $results[$key]['total'] = floor($results[$key]['total'] * 100) / 100;
                $results[$key]['good'][] = $goods;
            }
            $results = array_merge($results);
            $this->result($results, 0, '获取成功');
        }
    }

    public function cart_del()
    {
        $id = $this->request->post('id', '');
        $id = json_decode($id, true);
        if (count($id) <= 0) {
            $this->result([], 1, '操作失败');
        }
        $cartmodel = new Cart();
        $result = $cartmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }


    public function putorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'specid' => 'require',
            'addressid' => 'require'
        ], [
            'specid.require' => '规格ID不能为空',
            'addressid.require' => '地址ID不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $data['specid'] = json_decode($data['specid'] ?? '', true);
        if (empty($data['specid'])) {
            $this->result([], 1, '规格数据错误');
        }
        if (!empty($data['cartid'])) {
            $data['cartid'] = json_decode($data['cartid'] ?? '', true);
            if (empty($data['cartid'])) {
                $this->result([], 1, '购物车数据错误');
            }
        }
        //查询地址是否存在
        $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
        if (empty($address)) {
            $this->result([], 1, '地址信息错误存在');
        }
        $order = [
            'user_id' => $this->request->user_id,
            'ordersn' => reordersn(new Order()),
            'name' => $address['name'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'address' => $address['address'],
            'total' => 0,
            'remark' => $data['remark'] ?? '',
            'total' => 0,
            'ptotal' => 0
        ];
        $ordergoods = [];
        $sendmoney = 0; //起送金额
        foreach ($data['specid'] as $spec) {
            if (empty($spec['id'])  || empty($spec['number'])) {
                $this->result([], 1, '规格参数错误');
            }
            //查询规格是否存在
            $goodspec = (new GoodsSpec())->where(['isdel' => 1, 'id' => $spec['id']])->find();
            if (empty($goodspec)) {
                $this->result([], 1, '规格已下架，请重新提交订单');
            }
            //判断商品是否下架
            $goods = (new Goods())->where(['isdel' => 1, 'isSale' => 1, 'id' => $goodspec['goodid']])->find();
            if (empty($goods)) {
                $this->result([], 1, $goods['title'] . '商品已下架');
            }
            if ($goodspec['stock'] < $spec['number']) {
                $this->result([], 1, '库存不足');
            }
            //查找下面有没有相关服务人员
            $order['ptotal'] += $goodspec['price'] * $spec['number'];
            $ordergoods[] = [
                'ordersn' => $order['ordersn'],
                'classid' => $goods['classid'],
                'goodsid' => $goods['id'],
                'goodspecid' => $goodspec['id'],
                'title' => $goods['title'],
                'images' => $goods['images'],
                'name' => $goodspec['name'],
                'number' =>  $spec['number'],
                'unmit' => $goodspec['unmit'],
                'price' =>   $goodspec['price'],
                'total' => floor($spec['number'] * $goodspec['price'] * 100) / 100
            ];
        }
        $order['total'] = $order['ptotal'];
        $sendmoney = (new Config())->where('name', 'mintotal')->value('value') ?? 0;;
        if ($order['total'] < $sendmoney) {
            $this->result([], 1, '订货价不能低于最低价' . $sendmoney . '元，下单失败');
        }
        if (count($ordergoods) < 1 || count($order) < 1) {
            $this->result([], 1, '结算出错,请重试');
        }
        Db::startTrans();
        try {
            $id = (new Order())->insertGetId($order);
            (new OrderGoods())->allowfield(true)->saveAll($ordergoods);
            if (!empty($data['cartid'])) {
                (new Cart())->where(['id' => $data['cartid'], 'user_id' => $this->request->user_id])->delete();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '下单失败');
        }
        $this->result(['id' => $id], 0, '下单成功');
    }


    public function goods()
    {
        $data = $this->request->get();
        //范围内商家ID
        $result = (new Goods())->field('id,images,title,descs');
        if (!empty($data['title'])) {
            $result = $result->where('title|keywords', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['classid'])) {
            $result = $result->where('classid', $data['classid']);
        }
        if (!empty($data['recomm'])) {
            $result = $result->where('recomm', $data['recomm']);
        }
        if (!empty($data['isnew'])) {
            $result = $result->where('isnew', $data['isnew']);
        }

        $result = $result->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['images'] = json_decode($results['images'], true);
            $spec = (new GoodsSpec())->where(['goodid' => $results['id'], 'isdel' => 1])->order('is_default desc')->field('id,name,price,unmit,stock,starbuy')->select();
            foreach ($spec as $specs) {
                $specs['cart'] = (new Cart())->where(['user_id' => $this->request->user_id, 'specid' => $specs['id']])->value('number') ?? 0;
            }
            $results['spec'] = $spec;
        }
        $this->result($result, 0, '获取成功');
    }

    public function getclass()
    {
        $lists = (new PlatClass())->where('isshow', 1)->order('sort desc')->field('id,name,images')->select();
        $this->result($lists, 0, '获取成功');
    }

    public function getgoodsdetail()
    {
        $id  = $this->request->get('id/d', '0');
        $result = (new Goods())->where(['id' => $id, 'isdel' => 1])->field('id,title,classid,images,sale,isSale,descs,goodsDesc')->find();
        if ($result) {
            $result['images'] = json_decode($result['images'], true);
            $spec = (new GoodsSpec())->where(['goodid' => $result['id'], 'isdel' => 1])->order('is_default desc')->field('id,name,price,unmit,stock,starbuy')->select();
            foreach ($spec as $specs) {
                $specs['cart'] = (new Cart())->where(['user_id' => $this->request->user_id, 'specid' => $specs['id']])->value('number') ?? 0;
            }
            $result['spec'] = $spec;
        }
        $this->result($result, 0, '获取成功');
    }

    // public function getonecart()
    // {
    //     $specid  = $this->request->get('specid/d', '0');
    //     $number = (new Cart())->where(['user_id' => $this->request->user_id, 'specid' => $specid])->value('number') ?? 0;
    //     $this->result($number, 0, '获取成功');
    // }

    public function orderstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'status' => 'require|in:5,6'
        ], [
            'id.require' => '订单ID不能为空',
            'status.require' => '状态不能为空',
            'status.in' => '状态不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where(['id' => $data['id'], 'user_id' => $this->request->user_id])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        switch ($data['status']) {
            case '5':
                if ($order['status'] != 4) {
                    $this->result([], 1, '当前订单状态不可确认');
                }
                //完成订单
                $res = (new Order())->where('id', $data['id'])->update(['status' => $data['status'], 'finishtimes' => date('Y-m-d H:i:s')]);
                if ($res) {
                    $this->result([], 0, '操作成功');
                }
                $this->result([], 1, '操作失败，请重试');
                break;
            case '6':
                if ($order['status'] != 1 && $order['status'] != 2) {
                    $this->result([], 1, '订单状态不可取消');
                }
                //未配送订单直接取消
                if ($order['status'] == 1 || $order['status'] == 2) {
                    if ($order['review'] == 2 || $order['review'] == 3) {
                        $shouhou = 2;
                        $status = $order['status'];
                    } else {
                        $shouhou = 1;
                        $status = $data['status'];
                    }
                    Db::startTrans();
                    try {
                        (new Order())->where('id', $data['id'])->update([
                            'text' => $data['text'] ?? '',
                            'shouhou' => $shouhou,
                            'status' => $status,
                            'caceltimes' => date('Y-m-d H:i:s')
                        ]);
                        Db::commit();
                    } catch (\Exception $e) {
                        dump($e->getMessage());
                        Db::rollback();
                        $this->result([], 1, '操作失败，请重试');
                    }
                    $this->result([], 0, '操作成功');
                }
                break;
            default:
                $this->result([], 1, '订单状态不可修改');
                break;
        }
    }

    public function orderpay()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'type' => 'require|in:1'
        ], [
            'id.require' => '订单ID不能为空',
            'type.require' => '支付类型不能为空',
            'type.in' => '支付类型不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where(['id' => $data['id'], 'user_id' => $this->request->user_id])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        if ($order['status'] != 2 && $order['status'] != 1) {
            $this->result([], 1, '订单状态不可付款');
        }
        $arr[] = [
            'bank' => '中国建设银行',
            'name' => '张三',
            'cards' => '6217002920117497799',
        ];
        switch ($data['type']) {
            case '1':
                if ($order['review'] != 2 && $order['review'] != 1) {
                    $this->result([], 1, '订单已付款无需重复付款');
                }
                $data['images'] = $data['images'] ?? '';
                $images = json_decode($data['images'], true) ?? [];
                if (count($images) < 1) {
                    $this->result([], 1, '请上次正确的付款信息截图');
                }
                //完成订单
                $res = (new Order())->where('id', $data['id'])->update(['review' => 2, 'images' => $data['images'], 'payment' => $data['type']]);
                if ($res) {
                    $this->result([], 0, '操作成功');
                }
                $this->result([], 1, '操作失败，请重试');
                break;
            default:
                $this->result([], 1, '支付方式错误');
                break;
        }
    }


    public function orderlist()
    {
        $status = $this->request->get('status/d', '');
        $list = (new Order())->order(['id' => 'desc', 'status' => 'asc']);
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->where('user_id', $this->request->user_id)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $ordergoods = (new OrderGoods())->where(['ordersn' => $lists['ordersn']])->field('id,title,name,unmit,goodspecid,images,number,goodsid,price')->select();
            foreach ($ordergoods as $goods) {
                $goods['images'] = json_decode($goods['images'] ?? '', true);
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
            $lists['review_text'] = $lists->review_text;
            $lists['images'] = json_decode($lists['images'] ?? '', true);
        }
        $this->result($list, 0, '获取成功');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where('id', $id)->field('payment', true)->find();
        if ($list) {
            $list['status_text'] = $list->status_text;
            $list['review_text'] = $list->review_text;
            $goods = (new OrderGoods())->where('ordersn', $list['ordersn'])->field('id,ordersn,images,number,title,name,goodsid,goodspecid,price,unmit')->select();
            foreach ($goods as $good) {
                $good['images'] = json_decode($good['images'], true);
            }
            $list['images'] = json_decode($list['images'] ?? '', true);
            $list['time'] = strtotime($list['created']) + 120 * 60 - time();
            $list['time'] = $list['time'] < 0 ? 0 : $list['time'];
            $list['good'] = $goods;
        }
        $this->result($list, 0, '获取成功');
    }
}
